package healththink

class FacilityAttributeLink{
    Attribute attribute
    Facility facility

    static constraints = {
        attribute(blank:false)
    }
    
    static hasMany = [facilityAttributeRatings: FacilityAttributeRating]

    static mapping = {
        //attribute lazy:false
        //facility lazy: false 
    }
    
    boolean equals(FacilityAttributeLink fal){
        attribute.name.equals(fal.attribute.name)
    }
    
    int getAverageRating(){
        int total = 0
        int ratings = 0
        for(facilityAttributeRating in facilityAttributeRatings){
            total += facilityAttributeRating.rating
            ratings++
        }
        if(ratings==0){
            return 0
        }

        return total/ratings
    }
    
    static FacilityAttributeLink link(Attribute a, Facility f)
    {
        FacilityAttributeLink fal = 
            FacilityAttributeLink.findByAttributeAndFacility(
                a,
                f
            )
        if (!fal)
        {
            fal = new FacilityAttributeLink()	
            a?.addToFacilities(fal)
            f?.addToFacilityAttributes(fal)
            fal.save()
        }
        return fal
    }
    
    static void unlink(Attribute a, Facility f)
    {
        FacilityAttributeLink fal = 
            FacilityAttributeLink.findByAttributeAndFacility(
                a,
                f
            )
        
        if (fal)
        {
            //a?.removeFromFacilities(fal)
            //f?.removeFromFacilitiyAttributes(fal)
            fal.delete()
        }
        
    }
}
